import { Injectable } from '@nestjs/common';
import axios from 'axios';
import { WxConfig, wxModel } from './entities/config.entity';
import { SesstionKeyReqData } from './interface/SesstionKeyData.interface';
import { SubscribeMessageData } from './interface/SubscribeMessageData.interface';

@Injectable()
export class WxService {
  public async getSessionKey(js_code: string) {
    const { appid, secret } = await this.getConfig();
    const req = await axios.get<SesstionKeyReqData>(
      'https://api.weixin.qq.com/sns/jscode2session',
      {
        params: {
          appid,
          secret,
          js_code,
          grant_type: 'authorization_code',
        },
        responseType: 'json',
      },
    );
    const { openid, session_key, errcode, errmsg } = req.data;
    if (!errcode || errcode === 0) {
      return {
        success: true,
        openid,
        session_key,
      };
    } else {
      return {
        success: false,
        errmsg,
        errcode,
      };
    }
  }

  public async createConfig(
    appid: string,
    secret: string,
    template_id: string,
  ) {
    const reqData = await this.getAccessToken(appid, secret);
    if (reqData.access_token) {
      await wxModel.insertOne({
        appid,
        secret,
        access_token: reqData.access_token,
        template_id,
      });
    } else {
      console.log(reqData);
    }
  }

  public async updateSesstionToken() {
    const config = await this.getConfig();
    if (config) {
      const reqData = await this.getAccessToken(config.appid, config.secret);
      await wxModel.updateOne(
        { appid: config.appid },
        { $set: { access_token: reqData.access_token } },
      );
    }
  }

  async getAccessToken(appid: string, secret: string) {
    const req = await axios.get('https://api.weixin.qq.com/cgi-bin/token', {
      params: {
        grant_type: 'client_credential',
        appid,
        secret,
        // appid: 'wx0a3c2c0046db4354',
        // secret: '04feddd6f82999a77ec3651204c61e19',
      },
    });
    return req.data;
  }

  /**
   *
   * @param openid 用户id
   * @param awardId 奖励id
   * @param taskName
   * @param start_timestamp
   * @param duration
   */
  public async subscribeMessage(
    openid: string,
    awardId: string,
    taskName: string,
    start_timestamp: number,
    duration: string,
  ) {
    const date = new Date(start_timestamp);
    const year = date.getFullYear();
    const month = String(date.getMonth()).padStart(2, '0');
    const day = String(date.getDay()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minuate = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    const data: SubscribeMessageData = {
      time2: {
        value: `${year}-${month}-${day} ${hour}:${minuate}:${seconds}`,
      },
      phrase3: { value: '已到时' },
      thing4: { value: taskName },
      thing5: { value: duration },
    };
    const { access_token, template_id } = await this.getConfig();
    const req = await axios(
      'https://api.weixin.qq.com/cgi-bin/message/subscribe/send',
      {
        method: 'POST',
        params: {
          access_token,
        },
        data: {
          touser: openid,
          template_id,
          data,
          page: `pages/tab/schedule/summary?awardId=${awardId}`,
          miniprogram_state: 'trial',
        },
        responseType: 'json',
      },
    );
    if (req.data.errcode === 0) {
      return true;
    } else {
      console.log(req.data);
    }
  }

  public async getConfig() {
    const data = await wxModel.findOne<WxConfig>();
    return data;
  }
}
